package com.cloudkinto.service.invoice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.utils.MathUtils;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.extentity.InvoiceRecordDto;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.dic.vo.DicItemRes;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.finance.RechargeRecordService;
import com.cloudkinto.service.invoice.InvoiceRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.invoice.InvoiceTitleService;
import com.cloudkinto.service.invoice.vo.InvoiceRecordAddReq;
import com.cloudkinto.service.invoice.vo.InvoiceRecordDetailRes;
import com.cloudkinto.service.invoice.vo.InvoiceRecordUpdateReq;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author hjy
 * @since 2021-07-13
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class InvoiceRecordServiceImpl extends ServiceImpl<InvoiceRecordDao, InvoiceRecordDo> implements InvoiceRecordService {
    @Autowired
    private InvoiceRecordDao dao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private InvoiceTitleService invoiceTitleService;
    @Autowired
    private InvoiceTitleDao invoiceTitleDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private DicBusinessItemService dicBusinessItemService;
    @Autowired
    private RechargeRecordService rechargeRecordService;
    @Autowired
    private FileService fileService;
    @Autowired
    private  RechargeTypeDao rechargeTypeDao;

    @Override
    public SingleResult addInit(Long companyId) {
        Map map = new HashMap();
        //计算出可以开票得金额
        Double allAmount = dao.getSumCostRecord(companyId);
        Double hadInvoiceAmount = dao.getSumHadInvoiceAmount(companyId);
        map.put("leftAmount", MathUtils.numberFormat(MathUtils.sub(allAmount, hadInvoiceAmount)));

        //查询可以选择得发票抬头
        List<Map> invoiceList = invoiceTitleService.selectInvoiceListInit(companyId);
        map.put("invoiceTitleList", invoiceList);

        //查询上次开票使用的开票抬头
        CompanyDo companyDo = companyDao.selectById(companyId);
        if (companyDo != null && companyDo.getLastInvoiceTitleId() != null && companyDo.getLastInvoiceTitleId() != 0) {
            InvoiceTitleDo lastInvoiceTitle = invoiceTitleDao.selectById(companyDo.getLastInvoiceTitleId());
            map.put("lastInvoiceTitle", lastInvoiceTitle);
            map.put("lastInvoiceType", companyDo.getLastInvoiceType());
        }
        return SingleResult.success(map);
    }

    @Override
    public InvoiceRecordDo add(InvoiceRecordAddReq req, Long userId) {
        //前端新增发票 不可以先开 后充值，所以此处必有充值记录
        if (req.getInvoiceTitleId() == null || req.getInvoiceTitleId() == 0) {
            throw new BizExceptionI18(SysConstant.PLS_CHOOSE_INVOICE_TITLE);
        }
        InvoiceTitleDo et = invoiceTitleDao.selectById(req.getInvoiceTitleId());
        if (et == null) {
            throw new BizExceptionI18(SysConstant.INVOICE_TITLE_NOT_USE);
        }
        RechargeRecordDo rechargeRecordDo = rechargeRecordService.getById(req.getRechargeRecordId());
        if (rechargeRecordDo == null) {
            throw new BizExceptionI18(SysConstant.CHARGE_RECORD_NO_EXIST);
        }
        Long currency = req.getCurrency();
        if (rechargeRecordDo.getCurrency() == null) {
            RechargeTypeDo rechargeTypeDo = rechargeTypeDao.selectById(rechargeRecordDo.getRechargeTypeId());
            if (rechargeTypeDo  != null) {
                currency = "0".equals(rechargeTypeDo.getCurrency()) ? DicBusinessItemConstant.currency_rmb : DicBusinessItemConstant.currency_jpy;
            }
        }
        else {
            currency = rechargeRecordDo.getCurrency();
        }
        InvoiceRecordDo entityDo = new InvoiceRecordDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setBank(et.getBank());
        entityDo.setBankAccount(et.getBankAccount());
        entityDo.setCompanyAddress(et.getCompanyAddress());
        entityDo.setCompanyTelephone(et.getCompanyTelephone());
        entityDo.setInvoiceTitle(et.getInvoiceTitle());
        entityDo.setTaxNumber(et.getTaxNumber());
        if (DicBusinessItemConstant.currency_rmb.equals(currency)) {
            entityDo.setInvoiceAmount(rechargeRecordDo.getAmountRmb());
        }
        else {
            entityDo.setInvoiceAmount(rechargeRecordDo.getAmountJpy());
        }
        handlerAddBefore(entityDo, userId);
        if (entityDo.getStatus() == null || entityDo.getStatus() == 0L) {
            entityDo.setStatus(DicBusinessItemConstant.invoiceApplyStatus);
        }
        //固定月开先不生成记录，由定时器每月9号自动生成
        if (entityDo.getType() == 1) {
            if (entityDo.getInvoiceAmount() == null || entityDo.getInvoiceAmount() <= 0) {
                throw new BizExceptionI18(SysConstant.INPUT_RIGHT_INVOICE_AMOUNT);
            }
//            //一次开票，判断每月是否由开票记录
//            QueryWrapper<InvoiceRecordDo> queryWrapper = new QueryWrapper<>();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
//            String strDate = sdf.format(new Date());
//            queryWrapper.eq("company_id", entityDo.getCompanyId()).last(String.format(" and DATE_FORMAT(create_time,'%1$s') = '%2$s' limit 1", "%Y-%m", strDate));
//            InvoiceRecordDo record = dao.selectOne(queryWrapper);
//            if (record != null) {
//                throw new BizException("每月只可以开票一次!");
//            }
            dao.insert(entityDo);
        }

        rechargeRecordDo.setInvoiceRecordId(entityDo.getId());
        rechargeRecordService.updateById(rechargeRecordDo);
        //开票成功后，将开票抬头id 保存到t_company表中
        updateCompanyMsg(req.getInvoiceTitleId(), req.getType(), req.getCompanyId());
        return entityDo;
    }

    @Override
    public Long addRechargeInvoice(Long invoiceTitleId, Long rechargeId, Double amount, Long currency, Long companyId, Long userId) {
        InvoiceRecordAddReq req = new InvoiceRecordAddReq();
        req.setCompanyId(companyId);
        req.setInvoiceAmount(amount);
        req.setRechargeRecordId(rechargeId);
        req.setInvoiceTitleId(invoiceTitleId);
        req.setCurrency(currency);
        req.setType(1);
        InvoiceRecordDo invoiceRecordDo = add(req, userId);
        return invoiceRecordDo.getId();
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(InvoiceRecordDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(InvoiceRecordDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id, Long companyId) {
        InvoiceRecordDo et = dao.selectById(id);
        if (et == null) {
            throw new BizExceptionI18("no.order.info");
        }
        Map map = new HashMap();
        //计算出可以开票得金额
        double allAmount = dao.getSumCostRecord(companyId);
        double hadInvoiceAmount = dao.getSumHadInvoiceAmount(companyId);
        map.put("leftAmount", MathUtils.sub(allAmount, MathUtils.add(hadInvoiceAmount, et.getInvoiceAmount())));

        //查询可以选择得发票抬头
        List<Map> invoiceList = invoiceTitleService.selectInvoiceListInit(companyId);
        map.put("invoiceTitleList", invoiceList);
        InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();

        //判断下开票得状态
        if (!et.getStatus().equals(DicBusinessItemConstant.invoiceApplyStatus)) {
            String msg = DicBusinessItemConstant.invoicePassStatus.equals(et.getStatus()) ? "开票成功" : (DicBusinessItemConstant.invoiceNotPassStatus.equals(et.getStatus())
                    ? "驳回" : "");
            throw new BizExceptionI18(SysConstant.INVOiCE_CANNOT_UPDATE , msg );
        }
        BeanUtils.copyProperties(et, req);
        this.handlerDetailAfter(req);
        map.put("InvoiceRecord", req);
        return SingleResult.success(map);
    }

    @Override
    public InvoiceRecordUpdateReq update(InvoiceRecordUpdateReq req, Long userId) {
        InvoiceRecordDo entityDo = dao.selectById(req.getId());
        if (entityDo == null) {
            throw new BizExceptionI18("no.order.info");
        }
        //判断下开票得状态
        if (!entityDo.getStatus().equals(DicBusinessItemConstant.invoiceApplyStatus)) {
//            String msg = DicBusinessItemConstant.invoicePassStatus.equals(entityDo.getStatus()) ? "审核通过" : (DicBusinessItemConstant.invoiceNotPassStatus.equals(entityDo.getStatus())
//                    ? "作废" : (DicBusinessItemConstant.invoiceSuccessStatus.equals(entityDo.getStatus()) ? "开票成功" : "审核通过"));
            String msg = DicBusinessItemConstant.invoicePassStatus.equals(entityDo.getStatus()) ? "开票成功" : (DicBusinessItemConstant.invoiceNotPassStatus.equals(entityDo.getStatus())
                    ? "驳回" : "");
            throw new BizExceptionI18(SysConstant.INVOiCE_CANNOT_UPDATE , msg );
        }
        //更新时需要将本条开票记录 的开票金额另算
        if (!updateCheck(req.getCompanyId(), MathUtils.sub(req.getInvoiceAmount(), entityDo.getInvoiceAmount()))) {
            throw new BizExceptionI18(SysConstant.Invoice_Amount_Less);
        }
        if (req.getInvoiceTitleId() != null && req.getInvoiceTitleId() != 0L) {
            InvoiceTitleDo et = invoiceTitleDao.selectById(req.getInvoiceTitleId());
            if (et == null) {
                throw new BizExceptionI18(SysConstant.INVOICE_TITLE_NOT_USE);
            }

            //更新t_company表中的上次开票抬头id
            updateCompanyMsg(req.getInvoiceTitleId(), req.getType(), req.getCompanyId());
            //由titileId说明修改了该条开票信息的公司抬头，更新抬头信息
            entityDo.setBank(et.getBank());
            entityDo.setBankAccount(et.getBankAccount());
            entityDo.setCompanyAddress(et.getCompanyAddress());
            entityDo.setCompanyTelephone(et.getCompanyTelephone());
            entityDo.setInvoiceTitle(et.getInvoiceTitle());
            entityDo.setTaxNumber(et.getTaxNumber());
        }
        entityDo.setType(req.getType());
        entityDo.setInvoiceAmount(req.getInvoiceAmount());
//        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);

        return req;
    }

    public void updateCompanyMsg(Long invoiceTitleId, Integer type, Long companyId) {
        //开票成功后，将开票抬头id 保存到t_company表中
        CompanyDo companyDo = new CompanyDo();
        companyDo.setId(companyId);
        companyDo.setLastInvoiceTitleId(invoiceTitleId);
        companyDo.setLastInvoiceType(type);
        companyDao.updateById(companyDo);
    }

    //编辑校验
    private boolean updateCheck(Long companyId, double invoiceAmount) {
        double allAmount = dao.getSumCostRecord(companyId);
        double hadInvoiceAmount = dao.getSumHadInvoiceAmount(companyId);
        if ((MathUtils.sub(allAmount, hadInvoiceAmount)) < invoiceAmount) {
            return false;
        }
        return true;
    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(InvoiceRecordDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(InvoiceRecordDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        InvoiceRecordDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(InvoiceRecordDo entityDo, Long userId) {
//        entityDo.setDeleteBy(userId);
//        entityDo.setDeleteTime(new Date());
    }

    @Override
    public InvoiceRecordDetailRes detail(Long id) {
        InvoiceRecordDo entityDo = dao.selectById(id);
        InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();
        if (entityDo != null) {
            BeanUtils.copyProperties(entityDo, req);
        }
        handlerDetailAfter(req);
        return req;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(InvoiceRecordDetailRes res) {
        CompanyDo companyDo = companyDao.selectById(res.getCompanyId());
        if (companyDo != null) {
            res.setCompanyName(companyDo.getName());
        }
        RechargeRecordDo rechargeRecordDo = rechargeRecordService.getOne(new LambdaQueryWrapper<RechargeRecordDo>()
                .eq(RechargeRecordDo::getInvoiceRecordId, res.getId())
                .last("limit 1"));
        if (rechargeRecordDo != null) {
            res.setRechargeRecordId(rechargeRecordDo.getId());
            res.setRechargeAmount(rechargeRecordDo.getAmountRmb());
            res.setRechargeImage(fileService.getFilePath(rechargeRecordDo.getCertificateImageFileId()));
            if (rechargeRecordDo.getCurrency() == null) {
                RechargeTypeDo rechargeTypeDo = rechargeTypeDao.selectById(rechargeRecordDo.getRechargeTypeId());
                if (rechargeTypeDo != null) {
                    res.setCurrency("0".equals(rechargeTypeDo.getCurrency()) ? DicBusinessItemConstant.currency_rmb : DicBusinessItemConstant.currency_jpy);
                }
            }
            else {
                res.setCurrency(rechargeRecordDo.getCurrency());
            }
        }
        res.setApplyTime(res.getCreateTime());
        return res;
    }

    @Override
    public SingleResult pageInit(Long companyId) {
        Map result = new HashMap();
        //查询开票状态
        List<DicItemRes> invoiceStatusItems = dicBusinessItemService.getDicItemList(DicBusinessConstant.invoiceStatus);
        result.put("invoiceStatusList", invoiceStatusItems);

        Map map1 = new HashMap();
        map1.put("id", 0);
        map1.put("name", StringsUtil.createI18Message("固定月开"));
        Map map2 = new HashMap();
        map2.put("id", 1);
        map2.put("name", StringsUtil.createI18Message("一次开票"));
        List<Map> invoiceTypeList = Arrays.asList(map1, map2);
        result.put("invoiceTypeList", invoiceTypeList);

        if (companyId != null) {
            CompanyDo companyDo = companyDao.selectById(companyId);
            if (companyDo != null) {
                result.put("invoiceType", companyDo.getLastInvoiceType());
            }
        }
        return SingleResult.success(result);
    }

    @Override
    public List<InvoiceRecordDetailRes> getList(Map<String, String> map) {
        QueryWrapper<InvoiceRecordDo> wrapper = queryBuild(map);
        List<InvoiceRecordDo> list = this.list(wrapper);
        List<InvoiceRecordDetailRes> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
//        QueryWrapper<InvoiceRecordDo> wrapper = queryBuild(map);
        IPage<InvoiceRecordDto> page = pageInitDto(map);
//        page = this.page(page, wrapper);
        List<InvoiceRecordDto> recordDos = dao.listPageDto(page, map);
        List<InvoiceRecordDetailRes> resList = handlerListAfterDto(recordDos);
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<InvoiceRecordDetailRes> handlerListAfterDto(List<InvoiceRecordDto> list) {
        List<InvoiceRecordDetailRes> result = new ArrayList<>();
        for (InvoiceRecordDto et : list) {
            InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();
            BeanUtils.copyProperties(et, req);
            result.add(req);
        }
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<InvoiceRecordDetailRes> handlerListAfter(List<InvoiceRecordDo> list) {
        List<InvoiceRecordDetailRes> result = new ArrayList<>();
        for (InvoiceRecordDo et : list) {
            InvoiceRecordDetailRes req = new InvoiceRecordDetailRes();
            BeanUtils.copyProperties(et, req);
            CompanyDo companyDo = companyDao.selectById(req.getCompanyId());
            if (companyDo != null) {
                req.setCompanyName(companyDo.getName());
            }
            result.add(req);
        }
        return result;
    }

    private IPage<InvoiceRecordDo> pageInit(Map<String, String> map) {
        IPage<InvoiceRecordDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private IPage<InvoiceRecordDto> pageInitDto(Map<String, String> map) {
        IPage<InvoiceRecordDto> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<InvoiceRecordDo> queryBuild(Map<String, String> map) {
        QueryWrapper<InvoiceRecordDo> wrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(map.get("keyword"))) {
//            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.like("invoice_title",map.get("keyword"))
//                    .or().like("bank", map.get("keyword")));
//        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.eq("status", map.get("status")));
        }
        if (StringUtils.isNotBlank(map.get("type"))) {
            wrapper.and(invoiceRecordDoQueryWrapper -> invoiceRecordDoQueryWrapper.eq("`type`", map.get("type")));
        }
        return wrapper;
    }

    @Override
    public Map<String, Object> getInvoiceTitle(Long id) {
        InvoiceTitleDo invoiceTitleDo = invoiceTitleDao.selectById(id);
        Map<String, Object> msg = new HashMap<>();
        if (invoiceTitleDo != null) {
            msg.put("id", invoiceTitleDo.getId());
            msg.put("invoiceTitle", invoiceTitleDo.getInvoiceTitle());
            msg.put("taxNumber", invoiceTitleDo.getTaxNumber());
            msg.put("companyAddress", invoiceTitleDo.getCompanyAddress());
        }
        return msg;
    }


    /**
     * 暂停开票
     */
    @Override
    public String stop(Long companyId) {
        CompanyDo companyDo = companyDao.selectById(companyId);
        if (companyDo == null) {
            throw new BizExceptionI18(SysConstant.No_Company_Info);
        }
        companyDo.setLastInvoiceType(1);
        companyDao.updateById(companyDo);
        return "修改成功";
    }


}
